import copy
import datetime
import os
import math
import random
from dateutil import parser
import time
import options as opt

ROBOT_NAME = '老王'
silent_time = 1559057552
login_userid = 0
last_msg_list=[]

def chk_dir(path):
	if not os.path.exists(path):
		os.makedirs(path)

def get_work_dir():
	return 'data\\app\\'+'cn.awer.cq'


def get_data_path():
	return get_work_dir() + '\\users.db'


def str_emoji(emj_id):
	return '[CQ:emoji,id=%d]' % emj_id

def str_at(qq):
	"""
	返回@qq字符串
	"""
	return '[CQ:at,qq='+str(qq)+']'


def str_at_me():
	'''
	返回@qq字符串
	'''
	return '[CQ:at,qq=' + str(login_userid) + ']'

def str_time_delta(t,ty=0):
	'''
	时间戳转换为时间差字符串
	:param t:
	:return:
	'''
	time_array = time.localtime(t)  # 1970秒数
	time_str_other = time.strftime("%Y-%m-%d %H:%M:%S", time_array)
	datt = parser.parse(time_str_other)
	delta = datetime.datetime.now()-datt

	restr=''
	if(delta.days>0):
		restr='%d天前'%delta.days
	elif(delta.seconds>60*60):
		restr = '%d小时前' % (delta.seconds/60/60)
	elif (delta.seconds > 60):
		restr = '%d分钟前' % (delta.seconds / 60)
	else:
		restr='刚刚'
	if(ty==1):
		restr = '%s(%s)' % (time_str_other, restr)
	else:
		restr = '%s(%s)' % (restr, time_str_other)
	print(restr)
	return restr


def get_ms_stamp():
	'''
	当前时间的时间戳(至1970年秒数)
	'''
	seconds_from1970 = math.ceil(time.time() * 1000)
	return seconds_from1970


def get_second_stamp():
	'''
	当前时间的时间戳(至1970年秒数)
	'''
	seconds_from1970 = math.ceil(time.time())
	return seconds_from1970


def get_help():
	return opt.HELP_MSG


def list_friend_desc(friends):
	list_group_str = []
	for fr in friends:
		list_group_str.append('%s(%s)' % (fr['nickname'], fr['user_id']))

	return list_group_str

def list_group_desc():
	list_group_str= []
	for gp in opt.GROUP_OPTIONS:
		list_group_str.append('%s(%s)'%(gp['name'],gp['id']))
	
	return list_group_str

def get_group_cfg_path(group_id):
	cfg_file = get_work_dir() + '\\' + str(group_id)
	chk_dir(cfg_file)
	cfg_file = cfg_file + '\\config.dat'
	return cfg_file


def wirte_group_cfg(group_id, msg):
	cfg_file = get_group_cfg_path(group_id)
	f = open(cfg_file, 'w+')
	f.write(msg)
	f.close()


def get_group_default(_groupid)	:
	g_opt = {}
	for gc in opt.GROUP_DEFAULT_OPTIONS['opt']:
		g_opt[gc['id']] = gc['val']

	g_cfg = copy.deepcopy(opt.GROUP_DEFAULT_OPTIONS)
	g_cfg['opt'] = g_opt
	return g_cfg

def read_gourp_cfg(group_id):
	cfg = ''
	cfg_file = get_group_cfg_path(group_id)
	if os.path.exists(cfg_file):
		f = open(cfg_file, 'r')
		cfg = f.read()
		f.close()
	try:
		jo=eval(cfg)
		print(jo['opt']['enable_random_reply'])
	except BaseException as e:
		print('配置错误:'+str(e))
		return get_group_default(group_id)
	return jo

def get_board_qiyu_groupids():
	group_send = []
	for gp in opt.GROUP_OPTIONS:
		if gp['opt']['board_qiyu']:
			group_send.append(gp['id'])
	return group_send


def get_board_server_groupids():
	group_send = []
	for gp in opt.GROUP_OPTIONS:
		if gp['opt']['board_server']:
				group_send.append(gp['id'])
	return group_send


def init_group_options(groups):
	for g in groups:
		g_cfg=read_gourp_cfg(g['group_id'])
		g_cfg['id'] = g.get('group_id')
		g_cfg['name'] = g.get('group_name')

		opt.GROUP_OPTIONS.append(g_cfg)

def get_group_option(_groupid):
	for gp in opt.GROUP_OPTIONS:
		if gp['id']==_groupid:
			return gp['opt']

def get_repeat_msg(group_id, msg):
	find=False
	for i in range(len(last_msg_list)):
		if last_msg_list[i]['group_id']==group_id:
			find=True
			if msg == last_msg_list[i]['msg']:
				last_msg_list[i]['num'] += 1
				if last_msg_list[i]['num'] == 2:
					return last_msg_list[i]
			else:
				last_msg_list[i]['msg'] = msg
				last_msg_list[i]['num'] = 0
	
	if not find:
		last_info={'msg': msg, 'num':0, 'group_id':group_id}
		last_msg_list.append(last_info)
	
	return None


def get_random_rate(n):
	'''
	返回n/10的几率
	'''
	return random.randint(0, 10) < n


def is_silent():
	return get_second_stamp() < silent_time
